package com.hjj.homieMatching.config;

import com.hjj.homieMatching.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@Slf4j
public class UserAndBlogBloomFilterConfig {

    @Resource
    private RedissonClient redissonClient;

    @Bean("userBloomFilter")
    public RBloomFilter<Long> redisUserBloomFilter() {
        String userBloomFilterKey = RedisConstant.USER_BLOOM_FILTER_KEY;
        try {
            RBloomFilter<Long> userBloomFilter = redissonClient.getBloomFilter(userBloomFilterKey);
            if (!userBloomFilter.isExists()) {
                log.info("用户布隆过滤器：{} 不存在，正在初始化...", userBloomFilterKey);
                boolean b = userBloomFilter.tryInit(10000, 0.01); // 增加容量，减少误判率
                if (!b) {
                    log.error("用户布隆过滤器：{} 初始化失败", userBloomFilterKey);
                } else {
                    log.info("用户布隆过滤器：{} 初始化成功", userBloomFilterKey);
                }
            } else {
                log.info("用户布隆过滤器：{} 已存在，容量：{}, 误判率：{}", 
                        userBloomFilterKey, userBloomFilter.getSize(), userBloomFilter.getFalseProbability());
            }
            return userBloomFilter;
        } catch (Exception e) {
            log.error("用户布隆过滤器初始化异常：{}", e.getMessage(), e);
            throw new RuntimeException("用户布隆过滤器初始化异常", e);
        }
    }

    @Bean("blogBloomFilter")
    public RBloomFilter<Long> redisBlogBloomFilter() {
        String blogBloomFilterKey = RedisConstant.BLOG_BLOOM_FILTER_KEY;
        try {
            RBloomFilter<Long> blogBloomFilter = redissonClient.getBloomFilter(blogBloomFilterKey);
            if (!blogBloomFilter.isExists()) {
                log.info("博客布隆过滤器：{} 不存在，正在初始化...", blogBloomFilterKey);
                boolean b = blogBloomFilter.tryInit(10000, 0.01); // 增加容量，减少误判率
                if (!b) {
                    log.error("博客布隆过滤器：{} 初始化失败", blogBloomFilterKey);
                } else {
                    log.info("博客布隆过滤器：{} 初始化成功", blogBloomFilterKey);
                }
            } else {
                log.info("博客布隆过滤器：{} 已存在，容量：{}, 误判率：{}", 
                        blogBloomFilterKey, blogBloomFilter.getSize(), blogBloomFilter.getFalseProbability());
            }
            return blogBloomFilter;
        } catch (Exception e) {
            log.error("博客布隆过滤器初始化异常：{}", e.getMessage(), e);
            throw new RuntimeException("博客布隆过滤器初始化异常", e);
        }
    }

}
